<?php
function installation()
{
	$tables = array();
	$tables[0] = CM_LOGINTABLE;
	
	$fields = array();
	$fields[0] = 'userID';
		
	$recover = SQLRecover($tables, $fields, 'none');
	//return $recover['queryStatus'];
	if ($recover['queryStatus'] == 'DB Query yielded no results')
	{
		return 'There is a database error. This may be caused by a bug. Administration cannot proceed.';
	}
	else if ($recover['queryStatus'] == 'DB Success, no entries')
	{
		return 'create';
	}
	else
	{
		return 'in';
	}	
}

function secureLogIn()
{
	if (session('user') != 'null' && session('pass') != 'null')
	{
		if (verifyPassword($_SESSION['user'], $_SESSION['pass']))
		{
			if(file_exists('3rdPartyPHP/loginTickets.php'))
			{
/* 				echo session('ticket'); */
				if(checkTicket($_SESSION['user']))
				{
					return '1';
				}
				else
				{
					adminlog('out');
					/* echo '<script>window.location="'.INDEX.'home";</script>'; */
					return '0';
				}
			}
		}
		else
		{
			return '0';
		}
	}
	else
	{
		return '0';
	}
}

function trackLog($inOut)
{
	$logs = strtolower($inOut);
	$tableName = 'extras_userprofile';
	
	$fields = array();
	$fields[0] = 'lastLog'.$logs;
	
	$values = array();
	$values[0] = sqlDateNow();
	
	$whereClause='userName = "'.session('user').'"';
	
	$data = SQLUpdate($tableName, $whereClause, $fields, $values);
}

function adminlog($inOut)
{
	if ($inOut == 'in')
	{
		if (post('userName') != 'null' && post('password') != 'null')
		{
			if (verifyPassword($_POST['userName'], $_POST['password']))
			{
/* 				echo 'called_true'; */
				

				$_SESSION['user'] = $_POST['userName'];
				$_SESSION['pass'] = $_POST['password'];
				
				if(file_exists('3rdPartyPHP/loginTickets.php'))
				{
					generateTicket($_SESSION['user']);
				}
				trackLog($inOut);
				return true;
			}
			else
			{
/* 				echo 'called_false'; */
				return false;
			}
		}
		else
		{
/* 			echo 'called_nouser'; */
			return false;
		}
		
	}
	else if ($inOut == 'out')
	{
		trackLog($inOut);
		if(file_exists('3rdPartyPHP/loginTickets.php'))
		{
			closeTicket($_SESSION['user']);
		}
		unsetVar('SESSION', 'user') ;
		unsetVar('SESSION', 'pass');
		unsetVar('SESSION','ticket');
		return true;
	}
	else
	{
		return false;
	}
}

function secureEncrypt($password)
{
	$data = array();
	$encryption = crypt(time());
	$data['password'] = crypt(strip_tags($password), $encryption);
	
	$position = rand(2,5);
	$hash = rand(pow(10,$position-1), pow(10, $position)-1);
	
	$data['secureID'] = $position.$hash.strlen(strip_tags($password)).rand(1, 99999);
	return $data;
}

function createNewAccount($firstName, $lastName, $userName, $password, $email)
//CREATE NEW USER ACCOUNT
{
	$tables = array();
	$tables[0] = CM_LOGINTABLE;
	
	$search = array();
	$search[0] = '*';
	
	$whereClause = 'userName = "'.$userName.'"';
	
	$checker = SQLRecover($tables, $search, $whereClause);
	if ($checker['queryStatus'] == 'DB Query yielded no results')
	{
		return 'Failed to communicate with database';
	}
	else
	{
		if (!isset($checker['userName'][0]))
		{
			$dbPassword = secureEncrypt($password);
			$fields = array();
			$fields[0] = 'userName';
			$fields[1] = 'password';
			$fields[2] = 'firstName';
			$fields[3] = 'secureID';
			$fields[4] = 'lastName';
			
			$values = array();
			$values[0] = $userName;
			$values[1] = $dbPassword['password'];
			$values[2] = $firstName;
			$values[3] = $dbPassword['secureID'];
			$values[4] = $lastName;
			
			$insertNow = SQLInsert(CM_LOGINTABLE, $fields, $values);
			
			$tableName = 'extras_userprofile';
			
			$fields = array();
			$fields[0] = 'userName';
			$fields[1] = 'lastLogin';
			$fields[2] = 'lastLogout';
			$fields[3] = 'dateCreated';
			$fields[4] = 'email';
			
			$values = array();
			$values[0] = $userName;
			$values[1] = 'Never';
			$values[2] = 'Never';
			$values[3] = sqlDateNow();
			$values[4] = $email;
			
			$data = SQLInsert($tableName, $fields, $values);
			
			return $password;	
		}
		else
		{
			return 'A user is found with the same user name you provided. Please supply another user name.';
		}
	}
		
}

function updateExistingAccount($superAdmin, $oldPass, $newPass, $confPass, $username)
{
	//VERIFY IF OLD PASS WORKS
	if (verifyPassword($username, $oldPass) || $superAdmin == '1')
	{
		//VERIFY IF NEWPASS AND CONFPASS MATCH
		if ($newPass == $confPass)
		{
			//UPDATE THE WHOLE THING HERE
			$dbPassword = secureEncrypt($password);
			
			$tableName = CM_LOGINTABLE;
			$whereClause = 'userName = "'.$username.'";';
			
			$fields = array();
			$fields[0] = 'secureID';
			$fields[1] = 'password';
			
			$values = array();
			$values[0] = $dbPassword['secureID'];
			$values[1] = $dbPassword['password'];
			
			$db = SQLUpdate($tableName, $whereClause, $fields, $values);
			/* echo $db['queryStatus'].'<br>'.$db['traceSQL']; */
			return 'The entry was updated successfully.';
		}
		else
		{
			return 'The new password and the confirmation password do not match. Please re-enter both entries and try again.';
		}
	}
	else
	{
		return 'You have entered an incorrect password.';
	}
}

function deleteUser($username)
{
	$tableName = CM_LOGINTABLE;
	$whereClause = 'userName = "'.$username.'";';
	$db = SQLDelete ($tableName, $whereClause);
	return $db;
}

function verifyPassword($username, $password)
//VERIFY PASSWORD w/ SECUREID
{
	$tables = array();
	$tables[0] = CM_LOGINTABLE;
	
	$search = array();
	$search[0] = 'userName';
	$search[1] = 'password';
	$search[2] = 'secureID';
	
	$whereClause = 'userName = "'.$username.'"';
	
	$checker = SQLRecover($tables, $search, $whereClause);
	
	if($checker['queryStatus'] == 'DB Query success!')
	{
		$userInput = crypt(strip_tags($password), $checker['password'][0]);
		$numChar = str_split($checker['secureID'][0]);
		if (strlen($password) < 10)
		{
			if (strlen($password) == $numChar[$numChar[0]+1])
			{
				if ($userInput == $checker['password'][0])
				{
					return true;
				}
				else
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}
		else
		{
			if (strlen($password) == $numChar[$numChar[0]+1].$numChar[$numChar[0]+2])
			{
				if ($userInput == $checker['password'][0])
				{
					return true;
				}
				else
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}
	}
	else
	{
		return false;
	}
	
}

function displayAllUsers($all, $id)
//DISPLAY USERS
{
	if ($all == 'allusers')
	{
		$whereClause='none';
	}
	else
	{
		$whereClause='userName = "'.$id.'";';
	}
	$tables = array();
	$tables[0] = CM_LOGINTABLE;
	
	$fields = array();
	$fields[0] = 'userID id';
	$fields[1] = 'userName user';
	$fields[2] = 'firstName name';
	$fields[3] = 'lastName surname';
	$fields[4] = 'password pass';
	$fields[5] = 'secureID secure';
	
	$db = SQLRecover($tables, $fields, $whereClause);
	
	return $db;
}

?>